import React from 'react'
import { Drawer, Spin, DrawerProps } from 'antd'
import Loading from '../Loading'

export interface DrawerController {
  open: () => void
  close: () => void
  loading: (state: boolean) => void
  closeLoading: () => void
  visible: boolean
  loadingState: boolean
}

export function useDrawer(): DrawerController {
  const [visible, setVisible] = React.useState(false)
  const [loadingState, setLoadingState] = React.useState(false)

  return {
    open: () => setVisible(true),
    close: () => setVisible(false),
    loading: (state: boolean) => setLoadingState(state),
    closeLoading: () => setLoadingState(false),
    visible,
    loadingState,
  }
}

interface LHDrawerProps extends DrawerProps {
  drawer: DrawerController
  children?: React.ReactNode
}

const LHDrawer: React.FC<LHDrawerProps> = ({ drawer, children, ...props }) => {
  return (
    <Drawer
      destroyOnHidden
      open={drawer.visible}
      styles={{
        body: {
          padding: 12,
          backgroundColor: '#f0f2f5',
          overflow: 'hidden',
        }
      }}
      {...props}
    >
      {!drawer.loadingState && children}
      {drawer.loadingState && <Loading />}
    </Drawer>
  )
}

export default LHDrawer